﻿using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using Workbench.Models;
using Workbench.Persistance;

namespace Workbench.Operations
{
    public static class WordListOperations
    {
        public static List<AggregatedWordModel> GetAllUniqueWords(ProjectFileModel file)
        {
            return GetAllUniqueWords(new ProjectFileModel[] { file });
        }

        public static List<AggregatedWordModel> GetAllUniqueWords(IEnumerable<ProjectFileModel> files)
        {
            var textRepo = DBContext.Current.GetTextRepository();
            return textRepo.GetWordList(files);
        }

        public static Task<List<AggregatedWordModel>> GetAllUniqueWordsAsync(IEnumerable<ProjectFileModel> files)
        {
            return Task<List<AggregatedWordModel>>.Run(() => {
                return GetAllUniqueWords(files); 
            });
        }

        public static async Task ExportCSV(string filePath, IEnumerable<AggregatedWordModel> words)
        {
            using (var fs = File.OpenWrite(filePath))
            {
                var result = new StringBuilder();
                result.AppendLine(@"""Word"",""Frequency"",""Lemma Forms""");

                foreach (var word in words)
                {
                    result.AppendFormat("\"{0}\",", word.WordContent.Replace("\"", "\"\""));
                    result.AppendFormat("\"{0}\",", word.Freq.ToString().Replace("\"", "\"\""));
                    result.AppendFormat("\"{0}\"", word.GetConcatenatedBaseForms().Replace("\"", "\"\""));
                    result.AppendLine();
                }

                using (StreamWriter outfile = new StreamWriter(fs, Encoding.UTF8))
                {
                    await outfile.WriteAsync(result.ToString());
                }
            }
        }
    }
}
